package com.springapp.mvc.services;

import com.springapp.mvc.dao.GroupDao;
import com.springapp.mvc.dao.UserDao;
import com.springapp.mvc.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by dbychkov on 19.12.2014.
 */
@Component("userService")
public class UserServiceImpl implements UserService {

    private PasswordEncoder encoder = new ShaPasswordEncoder(256);

    @Autowired
    private UserDao userDao;

    @Autowired
    private GroupDao groupDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setGroupDao(GroupDao groupDao) {this.groupDao = groupDao; }

    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        com.springapp.mvc.entity.User user = userDao.getUserByName(name);
        if (user == null){
            String msg = String.format("User %s was not found", name);
            throw new UsernameNotFoundException(msg);
        }
        List<Role> roles = groupDao.getRolesByGroupId(user.getGroupId());
        Collection<? extends GrantedAuthority> auths = getAuthorities(roles);

        return new CustomUser(
                    user.getName(),
                    user.getPassword(),
                    true, // enabled
                    true, // not expired
                    true, // credentials not expired
                    true, // not locked
                    auths,
                    user.getId());
    }

    public Collection<? extends GrantedAuthority> getAuthorities(List<Role> roles) {
        List<GrantedAuthority> result = new ArrayList<>();
        for (Role r : roles){
            result.add(new SimpleGrantedAuthority(r.getName()));
        }
        return result;
    }

    @Override
    public void createUser(String name, String plainTextPassword, Long groupId) {
        String hashedPassword = encoder.encodePassword(plainTextPassword, name);
        userDao.createUser(name, hashedPassword, groupId);
    }

}

